/*
 * EarthdawnNetView.java
 */
package earthdawnnet.client;

import earthdawnnet.creationism.character.CreateCharacter;
import earthdawnnet.events.server.WhisperEvent;
import earthdawnnet.events.server.AddLineEvent;
import earthdawnnet.events.server.KickEvent;
import earthdawnnet.events.server.NameChangeEvent;
import earthdawnnet.util.IconProvider;
import java.awt.EventQueue;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import javax.swing.DefaultListModel;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.text.DefaultCaret;

/**
 * The application's main frame.
 */
public class EarthdawnNetView extends FrameView implements Observer
{
    private Client connection;
    private User player;
    private RollView rollView;
    private DefaultListModel dlm;
    private EarthdawnNetApp app;

    public EarthdawnNetView(EarthdawnNetApp app, Client c)
    {
        super(app);
        this.app = app;
        player = User.getInstance();
        connection = c;
        dlm = new DefaultListModel();
        initComponents();
        customInitComponents();
        
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++)
        {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
        {

            public void actionPerformed(ActionEvent e)
            {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
        {

            public void propertyChange(java.beans.PropertyChangeEvent evt)
            {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName))
                {
                    if (!busyIconTimer.isRunning())
                    {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName))
                {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName))
                {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName))
                {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    private void customInitComponents()
    {
        DefaultCaret caret = (DefaultCaret)chatArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        rollView = RollView.startUp(connection);
        getFrame().setIconImage(IconProvider.provide());
    }

    @Action
    public void showAboutBox()
    {
        if (aboutBox == null)
        {
            JFrame mainFrame = EarthdawnNetApp.getApplication().getMainFrame();
            aboutBox = new EarthdawnNetAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        EarthdawnNetApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        chatArea = new javax.swing.JTextArea();
        chatField = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        viewerList = new javax.swing.JList();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        connectMenuItem = new javax.swing.JMenuItem();
        changeServerMenuItem = new javax.swing.JMenuItem();
        changeNameMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        windowMenu = new javax.swing.JMenu();
        showDiceCupItem = new javax.swing.JMenuItem();
        sheetsMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        interactionMenu = new javax.swing.JPopupMenu();
        whisperItem = new javax.swing.JMenuItem();
        kickItem = new javax.swing.JMenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setAutoscrolls(true);
        jScrollPane1.setDoubleBuffered(true);
        jScrollPane1.setName("jScrollPane1"); // NOI18N
        jScrollPane1.setPreferredSize(new java.awt.Dimension(32000000, 96));

        chatArea.setColumns(20);
        chatArea.setEditable(false);
        chatArea.setLineWrap(true);
        chatArea.setRows(5);
        chatArea.setWrapStyleWord(true);
        chatArea.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        chatArea.setDoubleBuffered(true);
        chatArea.setName("chatArea"); // NOI18N
        chatArea.setPreferredSize(new java.awt.Dimension(800000000, 94));
        jScrollPane1.setViewportView(chatArea);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(earthdawnnet.client.EarthdawnNetApp.class).getContext().getResourceMap(EarthdawnNetView.class);
        chatField.setText(resourceMap.getString("chatField.text")); // NOI18N
        chatField.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        chatField.setName("chatField"); // NOI18N
        chatField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                chatFieldKeyPressed(evt);
            }
        });

        jScrollPane2.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        jScrollPane2.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane2.setMaximumSize(new java.awt.Dimension(200, 999999999));
        jScrollPane2.setMinimumSize(new java.awt.Dimension(80, 70));
        jScrollPane2.setName("jScrollPane2"); // NOI18N

        viewerList.setModel(dlm);
        viewerList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        viewerList.setToolTipText(resourceMap.getString("viewerList.toolTipText")); // NOI18N
        viewerList.setComponentPopupMenu(interactionMenu);
        viewerList.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
        viewerList.setMaximumSize(new java.awt.Dimension(50, 999999999));
        viewerList.setMinimumSize(new java.awt.Dimension(50, 90));
        viewerList.setName("viewerList"); // NOI18N
        viewerList.setPreferredSize(new java.awt.Dimension(50, 95));
        jScrollPane2.setViewportView(viewerList);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 499, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(chatField, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 408, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(earthdawnnet.client.EarthdawnNetApp.class).getContext().getActionMap(EarthdawnNetView.class, this);
        connectMenuItem.setAction(actionMap.get("toggleConnection")); // NOI18N
        connectMenuItem.setText(resourceMap.getString("connectMenuItem.text")); // NOI18N
        connectMenuItem.setName("connectMenuItem"); // NOI18N
        fileMenu.add(connectMenuItem);

        changeServerMenuItem.setAction(actionMap.get("changeServer")); // NOI18N
        changeServerMenuItem.setText(resourceMap.getString("changeServerMenuItem.text")); // NOI18N
        changeServerMenuItem.setName("changeServerMenuItem"); // NOI18N
        fileMenu.add(changeServerMenuItem);

        changeNameMenuItem.setAction(actionMap.get("changeName")); // NOI18N
        changeNameMenuItem.setText(resourceMap.getString("changeNameMenuItem.text")); // NOI18N
        changeNameMenuItem.setName("changeNameMenuItem"); // NOI18N
        fileMenu.add(changeNameMenuItem);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        windowMenu.setText(resourceMap.getString("windowMenu.text")); // NOI18N
        windowMenu.setDoubleBuffered(true);
        windowMenu.setName("windowMenu"); // NOI18N

        showDiceCupItem.setAction(actionMap.get("showDiceCup")); // NOI18N
        showDiceCupItem.setText(resourceMap.getString("showDiceCupItem.text")); // NOI18N
        showDiceCupItem.setName("showDiceCupItem"); // NOI18N
        windowMenu.add(showDiceCupItem);

        menuBar.add(windowMenu);

        sheetsMenu.setAction(actionMap.get("createCharacter")); // NOI18N
        sheetsMenu.setText(resourceMap.getString("sheetsMenu.text")); // NOI18N
        sheetsMenu.setName("sheetsMenu"); // NOI18N

        jMenuItem1.setAction(actionMap.get("createCharacter")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        sheetsMenu.add(jMenuItem1);

        menuBar.add(sheetsMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 711, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 536, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        interactionMenu.setName("interactionMenu"); // NOI18N

        whisperItem.setAction(actionMap.get("whisper")); // NOI18N
        whisperItem.setText(resourceMap.getString("whisperItem.text")); // NOI18N
        whisperItem.setName("whisperItem"); // NOI18N
        interactionMenu.add(whisperItem);

        kickItem.setAction(actionMap.get("kick")); // NOI18N
        kickItem.setText(resourceMap.getString("kickItem.text")); // NOI18N
        kickItem.setName("kickItem"); // NOI18N
        interactionMenu.add(kickItem);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void chatFieldKeyPressed(java.awt.event.KeyEvent evt)//GEN-FIRST:event_chatFieldKeyPressed
    {//GEN-HEADEREND:event_chatFieldKeyPressed
        switch (evt.getKeyCode())
        {
            case KeyEvent.VK_ENTER:
                String line = chatField.getText();
                chatField.setText("");
                connection.sendServerEvent(new AddLineEvent(line));
                break;
            default:
                break;
        }
    }//GEN-LAST:event_chatFieldKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem changeNameMenuItem;
    private javax.swing.JMenuItem changeServerMenuItem;
    private javax.swing.JTextArea chatArea;
    private javax.swing.JTextField chatField;
    private javax.swing.JMenuItem connectMenuItem;
    private javax.swing.JPopupMenu interactionMenu;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JMenuItem kickItem;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenu sheetsMenu;
    private javax.swing.JMenuItem showDiceCupItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JList viewerList;
    private javax.swing.JMenuItem whisperItem;
    private javax.swing.JMenu windowMenu;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    @Action
    public void showDiceCup()
    {
        if(rollView.isVisible())
        {
            rollView.setVisible(false);
            showDiceCupItem.setText("Show dice cup");
        }
        else
        {
            rollView.setVisible(true);
            showDiceCupItem.setText("Hide dice cup");
        }
    }

    @Action
    public void changeName()
    {
        String name = JOptionPane.showInputDialog("Enter a new name:");
        if(name != null && !name.equalsIgnoreCase(""))
        {
            player.setName(name);
            connection.sendServerEvent(new NameChangeEvent(name));
        }
    }
    @Action
    public void toggleConnection()
    {
        if(connection.isConnected())
        {
            connection.logout();
        }
        else
        {
            connection.login();
        }
        updateConnectionTextIntern();
    }

    @Action
    public void changeServer()
    {
        ServerData.askUserForData();
    }

    @Action
    public void whisper()
    {
        int selection = viewerList.getSelectedIndex();
        if(selection != -1)
        {
            String line = JOptionPane.showInputDialog("Enter message:");
            connection.sendServerEvent(new WhisperEvent(app.getId(selection), line));
        }
    }

    @Action
    public void kick()
    {
        int selection = viewerList.getSelectedIndex();
        if(selection != -1)
            connection.sendServerEvent(new KickEvent(app.getId(selection)));
    }

    @Action
    public void createCharacter()
    {
        CreateCharacter.startup();
    }
    
    // extern functions

    public void setViewerNames(final String[] names)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                updateViewerNamesIntern(names);
            }
        });
    }
    
    private void clearViewernames()
    {
            dlm.clear();
    }
    
    private void updateViewerNamesIntern(String[] names)
    {
        clearViewernames();
        dlm.setSize(names.length);
        for(int i = 0; i < names.length; i++)
        {
            dlm.set(i, names[i]);
        }
    }
    
    public void updateConnectionText()
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                updateConnectionTextIntern();
            }
        });
    }
    
    private void updateConnectionTextIntern()
    {
        if(connection.isConnected())
        {
            connectMenuItem.setText("Disconnect");
        }
        else
        {
            connectMenuItem.setText("Connect");
            clearViewernames();
        }
    }
    
    public void update(Observable o, Object arg)
    {
        final Collection<String> chat = (Collection<String>)arg;
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                updateChat(chat);
            }
        });
    }
    
    private void updateChat(Collection<String> chat)
    {
        
        chatArea.setText("");
        for(String s: chat)
        {
            chatArea.append(s+"\n");
        }
    }
}
